package com.jin.gulimall.cart.intercepter;


import com.jin.common.constant.AuthServerConstant;
import com.jin.common.constant.CartConstant;
import com.jin.common.vo.MemberRespVo;
import com.jin.gulimall.cart.vo.UserInfoTo;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sun.font.TrueTypeFont;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor extends HandlerInterceptorAdapter {
    //ThreadLocal本地线程，同一个线程内共享数据
    public static final ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        //若登录过，设置id
        if(session!=null){
            MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if(member!=null){
                userInfoTo.setUserId(member.getId());
            }
        }
        //若有cookies且其中存在user-key,设置到userInfo中
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if(name.equals(CartConstant.TEMP_CART_COOKIES_KEY)){
                userInfoTo.setUserKey(cookie.getValue());
                userInfoTo.setTempUser(true);
            }
        }
        //如果没有user-key就设置上去一个user-key
        String userKey = userInfoTo.getUserKey();
        if(StringUtils.isEmpty(userKey)){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //放入本地线程中
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 目标方法执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie("user-key", userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_CART_COOKIES_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
